package com.lzx.iteam.adapter;


import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import com.lzx.iteam.CloudContactDetailActivity;
import com.lzx.iteam.CloudDialerActivity;
import com.lzx.iteam.ContactDetailActivity;
import com.lzx.iteam.R;
import com.lzx.iteam.adapter.ContactEntryAdapter.ContactEntryHolder;
import com.lzx.iteam.bean.ChatContact;
import com.lzx.iteam.bean.CloudContact;
import com.lzx.iteam.bean.CloudGroup;
import com.lzx.iteam.bean.PhoneNumItem;
import com.lzx.iteam.contactssearch.conversion.PinyinSearch;
import com.lzx.iteam.net.AsynHttpClient;
import com.lzx.iteam.net.GetChatGroupMsg;
import com.lzx.iteam.net.GetInviteContactMsg;
import com.lzx.iteam.net.LocalLogin;
import com.lzx.iteam.util.*;
import com.lzx.iteam.widget.RoundImageView;
import io.rong.imageloader.core.DisplayImageOptions;
import io.rong.imageloader.core.ImageLoader;
import io.rong.imageloader.core.listener.ImageLoadingListener;
import io.rong.imageloader.core.assist.ImageScaleType;
import io.rong.imageloader.core.listener.SimpleImageLoadingListener;
import io.rong.imageloader.core.display.FadeInBitmapDisplayer;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

import io.rong.imageloader.core.display.RoundedBitmapDisplayer;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

public class CloudContactAdapter extends AmazingAdapter implements View.OnClickListener,
      View.OnLongClickListener {
    private PreferenceUtil prefUtil;
    private LayoutInflater mInflater;
    private ArrayList<CloudContact> mContactList = new ArrayList<CloudContact>();
    public ArrayList<CloudContact> mSelectedContactList = new ArrayList<CloudContact>();
    public ArrayList<CloudContact> mBackUpContactList = new ArrayList<CloudContact>();//缓存全部联系人的数据
    private ArrayList<ChatContact> mContactIdSelected = new ArrayList<ChatContact>();

    private ArrayList<String> mNameCard = new ArrayList<String>();

    private CloudDialerActivity mContext;
    private int mTotalCount;
    private int mGroupType;
    private String mGroupName;
    private String mMyName;
    private long mGroupId;
    private View mTouchedView;
    private boolean mInterrupted;
    private boolean mIsFuzzy;
    public static boolean opening = true;
    private String section;
    private boolean mIfCheckBoxShow = false;
    public boolean mIsShowSelected = false;
    //public Long selectedId;


    //    private boolean mIfCheckBoxShow = false;
//    private ArrayList<Long> mContactIdSelected = new ArrayList<Long>();
    private ImageLoadingListener animateFirstListener;
    private DisplayImageOptions options;
    protected ImageLoader imageLoader;
    private String contactId;
    private  static final int MSG_INVITE_CONTACT=1000;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case MSG_INVITE_CONTACT:
                    if(msg.arg1==0){
                        CloudContact cloudContact=(CloudContact)msg.obj;
                        CommonCodeUtil.launchSendMessage(
                              mContext, cloudContact.contact_phone,
                              "【" + mMyName + "】邀请你加入【" + mGroupName + "】，点击" + AsynHttpClient.HTTP_TEAM_DOWNLOAD + " 接受邀请，加入企业，免费聊天。"
                        );
                    }else if(msg.arg1==1){
                        Toast.makeText(mContext,"对不起，该成员号码限制公开",Toast.LENGTH_LONG).show();
                    }
                    break;
            }
        }
    };

    public CloudContactAdapter(CloudDialerActivity c, CloudGroup group, ArrayList<CloudContact> contactList, ImageLoader imageLoader) {
        mContext = c;
        mInflater = LayoutInflater.from(c);
        if (contactList != null) {
            mContactList.addAll(contactList);
        } else {
            mContactList.clear();
        }
        prefUtil = PreferenceUtil.getInstance(mContext);
        options = new DisplayImageOptions.Builder()
              //.showStubImage(R.drawable.default_cloud_image)
              .showImageForEmptyUri(R.drawable.default_cloud_image)
              .showImageOnFail(R.drawable.default_cloud_image)
              .cacheInMemory(true)
              .cacheOnDisc(true)
              //.displayer(new RoundedBitmapDisplayer(Constants.dip2px(mContext,20)))
              .imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2)
              .bitmapConfig(Bitmap.Config.RGB_565)
              .build();
        animateFirstListener = new AnimateFirstDisplayListener();
        this.imageLoader = imageLoader;
        mTotalCount = group.contactCount;
        mGroupName = group.groupName;
        mGroupId = group.groupId;

        mNameCard = (ArrayList<String>) prefUtil.getCloudContact(Constants.CONTACT_NAME_CARD);
        if (mNameCard != null && mNameCard.size() > 0){
            mMyName = mNameCard.get(0);
        }
        if (StringUtil.isEmpty(mMyName)){
            mMyName = PreferenceUtil.getInstance(mContext).getString("my_user_name","");
        }
    }

    public void setCurrentContactId(String contactId) {
        this.contactId = contactId;
    }

    private static class AnimateFirstDisplayListener extends
          SimpleImageLoadingListener {

        static final List<String> displayedImages = Collections
              .synchronizedList(new LinkedList<String>());

        @Override
        public void onLoadingComplete(String imageUri, View view,
                                      Bitmap loadedImage) {
            if (loadedImage != null) {
                ImageView imageView = (ImageView) view;
                boolean firstDisplay = !displayedImages.contains(imageUri);
                if (firstDisplay) {
                    //FadeInBitmapDisplayer.animate(imageView, 500);
                    displayedImages.add(imageUri);
                }
            }
        }


    }


    public void setInterrupted(boolean interrupted) {
        mInterrupted = interrupted;
    }

    public void updateCloudGroup(CloudGroup group) {
        mTotalCount = group.contactCount;
        mGroupType = group.groupType;
        mGroupName = group.groupName;
        mGroupId = group.groupId;

    }

    public void updateData(ArrayList<CloudContact> contactList, boolean isFuzzy) {
        if (contactList != null) {
            mContactList.clear();
            mContactList.addAll(contactList);
            mIsFuzzy = isFuzzy;


            int validsum = 0;
            int invalidsum = 0;

            for (CloudContact cloudContact : mContactList) {
                String userId = cloudContact.userId;
                if (isHaveUnClickable && userId.equals("0")) {
                    invalidsum++;
                } else //if( mSelectedContactList.contains(cloudContact) == true )
                {
                    for (CloudContact exsitone : mSelectedContactList) {
                        if (exsitone.contactId.equals(cloudContact.contactId)) {
                            validsum++;
                            break;
                        }
                    }
                }
            }

            if ((invalidsum + validsum) == mContactList.size()) {
                mContext.mCbSelectAll.setChecked(true);
            } else {
                mContext.mCbSelectAll.setChecked(false);
            }


            notifyDataSetChanged();
        }
    }

    public void appendData(ArrayList<CloudContact> contactList) {
        mContactList.addAll(contactList);
        notifyDataSetChanged();
    }

    //    public void setIfCheckBoxShow(boolean show) {
//        this.mIfCheckBoxShow = show;
//        mContactIdSelected.clear();
////        selectedId = null;
//    }
//    
//    public void setIfCheckBoxShowNoClear(boolean show) {
//        this.mIfCheckBoxShow = show;
//    }
//    
//    public void clearSelected(){
//        mContactIdSelected.clear();
//    }
    public void setSection(String section) {
        this.section = section;
    }

    @Override
    public String[] getSections() {
        String[] sect = new String[1];
        if (!StringUtil.isEmpty(section)) {
            sect[0] = section;
        } else {
            sect[0] = "云通讯录";
        }
        return sect;
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {

    }

    @Override
    public int getCount() {
        return (mContactList != null ? mContactList.size() : 0);
    }

    @Override
    public CloudContact getItem(int position) {
        if (getItemViewType(position) == Constants.TYPE_NORMAL) {
            return mContactList != null ? mContactList.get(position) : null;
        } else {
            return null;
        }
    }

    @Override
    public int getItemViewType(int position) {
        /*
        if (position == 0) {
            return Constants.TYPE_HEADER;
        } else if (position < getCount() - 1) {
            return Constants.TYPE_NORMAL;
        }
        else {
            return Constants.TYPE_FOOTER;
        }*/
        /*
        if(position == 0){
            return Constants.TYPE_HEADER;
        }else{
            return Constants.TYPE_NORMAL;
        }*/
        return Constants.TYPE_NORMAL;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    protected void onNextPageRequested(int page) {

    }

    @Override
    protected void bindSectionHeader(View view, int position, boolean displaySectionHeader) {
        displaySectionHeader = false;
        if (displaySectionHeader) {
            TextView sectionTitle = (TextView) view.findViewById(R.id.composer_header);
            if (sectionTitle == null) {
                sectionTitle = (TextView) view.findViewById(R.id.header);
                if (sectionTitle != null) {
                    //sectionTitle.setVisibility(View.VISIBLE);
                    sectionTitle.setText(getSections()[getSectionForPosition(position)]);
                }
            } else {
                //sectionTitle.setVisibility(View.VISIBLE);
                sectionTitle.setText(getSections()[getSectionForPosition(position)]);
            }

        } else if (Constants.TYPE_FOOTER != getItemViewType(position)) {
            TextView sectionTitle = (TextView) view.findViewById(R.id.composer_header);
            if (sectionTitle == null) {
                sectionTitle = (TextView) view.findViewById(R.id.header);
                if (sectionTitle != null) {
                    sectionTitle.setVisibility(View.GONE);
                }
            } else {
                sectionTitle.setVisibility(View.GONE);
            }

        }
    }

    @Override
    public View getAmazingView(int position, View convertView, ViewGroup parent) {
        int p = getItemViewType(position);

        if (p == Constants.TYPE_NORMAL) {
            final CloudContact cloudContact = getItem(position);

            ContactEntryHolder holder = null;
            /*
            if (convertView == null || convertView.getTag(R.layout.cloud_contact_item) == null) {
                convertView = mInflater.inflate(R.layout.cloud_contact_item, null);

                holder = new ContactEntryHolder();
                holder.nameTextView = (TextView) convertView.findViewById(R.id.search_contact_name);
                holder.nameTextView.setTextColor(nameColor);
                //ADD BY LK (云号码群列表字体和软件字体不一致)
                holder.nameTextView.setTextSize(mContext.mFontSizeValue);
                holder.timesContactedView = (TextView) convertView.findViewById(R.id.contact_count);
                holder.numberTextView = (TextView) convertView.findViewById(R.id.search_contact_number);
                holder.numberTextView.setTextColor(phoneColor);
                holder.orgTextView = (TextView) convertView.findViewById(R.id.organizational);
                holder.orgTextView.setTextColor(jobTitleColor);
                holder.checkBox = (CheckBox) convertView.findViewById(R.id.isSel);
                holder.quickContact = (ImageView) convertView.findViewById(R.id.quickContact);
                holder.maskImg = (ImageView) convertView.findViewById(R.id.iv_cloud_mask);
                holder.cloudStatus = (ImageView) convertView.findViewById(R.id.iv_cloud_status);
                holder.inviteImg = (ImageView) convertView.findViewById(R.id.iv_invite_icon);
                convertView.setTag(R.layout.cloud_contact_item, holder);
            } else {
                holder = (ContactEntryHolder) convertView.getTag(R.layout.cloud_contact_item);
            }
            */

            ///////////////////
            if (convertView == null /*|| convertView.getTag(R.layout.cloud_contact_item) == null*/) {
                convertView = mInflater.inflate(R.layout.cloud_contact_item, null);
            }
            holder = (ContactEntryHolder) convertView.getTag();
            if (holder == null) {
                holder = new ContactEntryHolder();
            }
            holder.nameTextView = (TextView) convertView.findViewById(R.id.search_contact_name);
            holder.nameTextView.setTextColor(nameColor);
            //ADD BY LK (云号码群列表字体和软件字体不一致)
            holder.nameTextView.setTextSize(mContext.mFontSizeValue);
            holder.timesContactedView = (TextView) convertView.findViewById(R.id.contact_count);
            holder.numberTextView = (TextView) convertView.findViewById(R.id.search_contact_number);
            holder.numberTextView.setTextColor(phoneColor);
            holder.orgTextView = (TextView) convertView.findViewById(R.id.organizational);
            holder.orgTextView.setTextColor(jobTitleColor);
            holder.checkBox = (CheckBox) convertView.findViewById(R.id.isSel);
            holder.quickContact = (RoundImageView) convertView.findViewById(R.id.quickContact);
            holder.quickContact.setRectAdius(Constants.dip2px(mContext,20));
            //holder.maskImg = (ImageView) convertView.findViewById(R.id.iv_cloud_mask);
            holder.cloudStatus = (ImageView) convertView.findViewById(R.id.iv_cloud_status);
            holder.inviteImg = (ImageView) convertView.findViewById(R.id.iv_invite_icon);
            convertView.setTag(holder);
            /*    
            } 
            else {
                holder = (ContactEntryHolder) convertView.getTag(R.layout.cloud_contact_item);
            }
            */


            //bindSectionHeader(convertView, position, false);


            if (mInterrupted) {
                holder.quickContact.setVisibility(View.INVISIBLE);
                return convertView;
            }

            holder.contactId = Long.valueOf(cloudContact.contactId);
            /////////////////////
            holder.inviteImg.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    inviteContact(cloudContact.contactId);
                }
            });
            /*if (selectedId != null && selectedId.intValue() == holder.contactId.intValue()) {
                setSelectedStatus(convertView);
            } else {
                this.clearSelectedStatus(convertView);
            }*/

            holder.quickContact.setVisibility(View.VISIBLE);

            if (cloudContact.keyType == AsynHttpClient.KEY_TYPE_CONTACT_NAME) {
                Spannable hlName = hightLightMatch(cloudContact.contactName,
                      hightLightColor, cloudContact.keyStartLocation, cloudContact.keyCount);
                holder.nameTextView.setText(hlName);
            } else {
                holder.nameTextView.setText(cloudContact.contactName);
            }
			
            /*
            holder.nameTextView.setText(cloudContact.contactName);
            PinyinSearch mPinyinSearch = PinyinSearch.getInstance(null);
            boolean nameMatch = false;
            if (!StringUtil.isEmpty(cloudContact.contactName) && mPinyinSearch.mContactIdPosition != null) {
                PinyinSearch.HighLightFormat result = mPinyinSearch.mContactIdPosition.get(Long.valueOf(contactId));
                if (result != null) {
                    nameMatch = true;
                    Spannable wordtoSpan = new SpannableString(cloudContact.contactName);
//                    Pattern pattern = Pattern.compile("\\s");
//                    Matcher matcher = pattern.matcher(nameValue);
//                    if (matcher.find()) {
//                        int count = matcher.groupCount();
//                        for (int i = 0; i < count; i++) {
//                            String str = matcher.group(i);
//                        }
//                    }
                    int positionNew = 0;
                    int startPosition = -1;
                    int blankNumber = 0;
                    int rankLevel = result.rankLevel;
                    int nameLength = result.matchnameLength;
                    if (cloudContact.contactName.indexOf(" ") != -1) {
                        char[] valueArray = cloudContact.contactName.toCharArray();
                        for (int i = 0; i < valueArray.length; i++) {
                            if (!Character.isWhitespace(valueArray[i])) {
                                if (positionNew == rankLevel) {
                                    startPosition = i;
                                    int length = 0;
                                    for (int j = i + 1; j < valueArray.length; j++) {
                                        if (!Character.isWhitespace(valueArray[j])) {
                                            length++;
                                            if (length == nameLength) {
                                                break;
                                            }
                                        } else {
                                            blankNumber++;
                                        }
                                    }
                                    break;
                                }
                                positionNew++;
                            }
                        }
                        rankLevel = startPosition;
                        nameLength += blankNumber;
                    }
                    if (selectedId != null) {
                        if (selectedId.equals(holder.contactId)) {
                            hightLightColor = Color.WHITE;
                        } else {
                            hightLightColor = highLightColorBck;
                        }
                    } else {
                        hightLightColor = highLightColorBck;
                    }
                    if (rankLevel >= cloudContact.contactName.length() && nameLength > 0) {

                    } else if (((rankLevel + nameLength) > cloudContact.contactName.length()) && (rankLevel < cloudContact.contactName.length()) && rankLevel >= 0) {
                        wordtoSpan.setSpan(new ForegroundColorSpan(hightLightColor), rankLevel, cloudContact.contactName.length(),
                                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    } else {
                        wordtoSpan.setSpan(new ForegroundColorSpan(hightLightColor), rankLevel, rankLevel
                                + nameLength, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    }
                    holder.nameTextView.setText(wordtoSpan);
                }
            }
            */












            // on server they trade the phone num & contact in the same type now
            holder.numberTextView.setVisibility(View.GONE);
            //String phoneNum = getPhoneNumStr(cloudContact.contactPhoneNum);
            /*holder.numberTextView.setVisibility(!TextUtils.isEmpty(phoneNum)
                    ? View.VISIBLE : View.GONE);
            if (!mIsFuzzy && cloudContact.keyType == AsynHttpClient.KEY_TYPE_CONTACT_NAME
                    && cloudContact.keyStartLocation == 0 && cloudContact.keyCount == 0) {
                Spannable hlPhoneNum = hightLightMatch(phoneNum, 
                        hightLightColor, 0, phoneNum.length());
                holder.numberTextView.setText(hlPhoneNum);
            } else {
                holder.numberTextView.setText(phoneNum);
            }*/
            holder.orgTextView.setVisibility(View.GONE);

            /*holder.orgTextView.setVisibility(!TextUtils.isEmpty(cloudContact.contactRemarks)
                    ? View.VISIBLE : View.GONE);
            if (cloudContact.keyType == AsynHttpClient.KEY_TYPE_CONTACT_REMARKS) {
                Spannable hlRemarks = hightLightMatch(cloudContact.contactRemarks, 
                        hightLightColor, 
                        cloudContact.keyStartLocation, 
                        cloudContact.contactRemarks.length());
                holder.orgTextView.setText(hlRemarks);
            } else {
                holder.orgTextView.setText(cloudContact.contactRemarks);
            }
            */
            // cloudContact.contactedCount
            if (mGroupType == CloudGroupAdapter.GROUP_TYPE_PRIVATE
                  && mContactList.size() > 0 && mContext.mShowTimesContacted) {
                holder.timesContactedView.setText(
                      mContext.getString(R.string.call_count, mContactList.size()));
                //holder.timesContactedView.setVisibility(View.VISIBLE);
                holder.timesContactedView.setVisibility(View.GONE);
            } else {
                holder.timesContactedView.setVisibility(View.GONE);
            }

            /*if (!cloudContact.userId.equals("0")) {
                holder.cloudStatus.setVisibility(View.VISIBLE);
                holder.inviteImg.setVisibility(View.GONE);
            } else {
                if (isHaveUnClickable) {
                    holder.checkBox.setButtonDrawable(R.drawable.check_unclickable);
                } else {
                    holder.checkBox.setButtonDrawable(R.drawable.checkbox_sel_bulksms);
                }
                holder.cloudStatus.setVisibility(View.GONE);
                holder.inviteImg.setVisibility(View.VISIBLE);
            }*/

            if (!cloudContact.userId.equals("0")) {//注册的
                holder.inviteImg.setVisibility(View.GONE);
                holder.cloudStatus.setVisibility(View.VISIBLE);
            } else {//未注册的
                holder.inviteImg.setVisibility(View.VISIBLE);
                holder.cloudStatus.setVisibility(View.GONE);
            }
            if (mIfCheckBoxShow) {
                holder.checkBox.setVisibility(View.VISIBLE);
                holder.inviteImg.setVisibility(View.GONE);
//                holder.cloudStatus.setVisibility(View.GONE);//绿点暂时隐藏
                holder.checkBox.setChecked(false);
                if (!cloudContact.userId.equals("0")) {//注册的
                    holder.checkBox.setButtonDrawable(R.drawable.checkbox_sel_bulksms);
                } else {//未注册的
                    if (isHaveUnClickable) {
                        holder.checkBox.setButtonDrawable(R.drawable.check_unclickable);
                    } else {
                        holder.checkBox.setButtonDrawable(R.drawable.checkbox_sel_bulksms);
                    }
                }
                ChatContact chatContact = null;
//                if (cloudContact.contactPhoneNum.size() > 0) {
//                    chatContact = new ChatContact(cloudContact.userId + "", cloudContact.contactName, cloudContact.contactPhoneNum.get(0).phoneNum, cloudContact.contactId + "");
//                } else {
                chatContact = new ChatContact(cloudContact.userId + "", cloudContact.contactName,  cloudContact.contactId + "");
//                }
                for (int i = 0; i < mContactIdSelected.size(); i++) {
                    if (chatContact.equals(mContactIdSelected.get(i))) {
//                if (mContactIdSelected.contains(chatContact)) {
                        holder.checkBox.setChecked(true);
                    }
                }
            } else {
                holder.checkBox.setVisibility(View.GONE);
            }

            String imgPath = cloudContact.contact_image == null ? "" : cloudContact.contact_image;
            if(!StringUtil.isEmpty(imgPath)){
                imageLoader.displayImage(imgPath, holder.quickContact, options, animateFirstListener);
            }
            //convertView.setTag(2, cloudContact);
            holder.item = cloudContact;
            convertView.setOnClickListener(this);
            convertView.setOnLongClickListener(this);
            return convertView;
        } else if (p == Constants.TYPE_HEADER) {
            TextView sectionText = (TextView) mInflater.inflate(
                  R.layout.item_composer_header, null);
            TextView text = (TextView) sectionText.findViewById(R.id.header);
            int section = getSectionForPosition(position);

            text.setText(getSections()[section].toString());
            bindSectionHeader(sectionText, position, true);

            return sectionText;
        } else {
            View footerView = mInflater.inflate(R.layout.search_contact_footerview, null);
            footerView.setBackgroundResource(R.drawable.list_selector);
            TextView line = (TextView) footerView.findViewById(R.id.footer_line);
            TextView matchText = (TextView) footerView.findViewById(R.id.footer_match_text);
            TextView searchText = (TextView) footerView.findViewById(R.id.footer_search_text);

            line.setTextColor(nameColor);
            line.setText("_____________________");

            matchText.setTextColor(jobTitleColor);
            matchText.setText(mContext.getString(R.string.cloud_contact_count,
                  getCount() - 2, mTotalCount));

            searchText.setTextColor(phoneColor);
            searchText.setText(mContext.getString(R.string.for_more));

            footerView.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    mContext.appendCloudContactListReq();
                }
            });
            return footerView;
        }
    }

    private String getPhoneNumStr(ArrayList<PhoneNumItem> phoneNumList) {
        if (phoneNumList == null || phoneNumList.size() == 0) {
            return "";
        }

        StringBuilder phoneNum = new StringBuilder();
        phoneNum.append(phoneNumList.get(0).phoneNum);
        for (int i = 1; i < phoneNumList.size(); i++) {
            phoneNum.append('\n').append(phoneNumList.get(i).phoneNum);
        }
        return phoneNum.toString();
    }

    @Override
    public void configurePinnedHeader(View header, int position, int alpha) {
        /*
        TextView sectionHeader = (TextView) header.findViewById(R.id.header);

        int section = getSectionForPosition(position);
        if (section != -1) {
            sectionHeader.setText(getSections()[section]);
        }*/
    }

    // only one setcion
    public int getPositionForSection(int section) {
        if (section > 0)
            return -1;
        else
            return 0;
    }

    public int getSectionForPosition(int position) {
        return 0;
    }

    public int getPinnedHeaderState(int position) {
        if (position < 0 || getCount() == 0) {
            return Constants.PINNED_HEADER_GONE;
        }

        // The header should get pushed up if the top item shown
        // is the last item in a section for a particular letter.
        int section = getSectionForPosition(position);
        int nextSectionPosition = getPositionForSection(section + 1);
        if (nextSectionPosition != -1 && position == nextSectionPosition - 1) {
            return Constants.PINNED_HEADER_PUSHED_UP;
        }

        return Constants.PINNED_HEADER_VISIBLE;
    }

    public static Spannable hightLightMatch(String name, int hlColor, int keyStart, int keyCount) {
        Spannable wordtoSpan = new SpannableString(name);
        if (keyStart < 1 && keyCount < 1) {
            return wordtoSpan;
        }

        if (keyStart >= name.length() && keyCount > 0) {
            Log.w(TAG, "unexpected keyStart: " + keyStart + " keyCount: " + keyCount);
        } else if (((keyStart + keyCount) > name.length()) && (keyStart < name.length())
              && keyStart >= 0) {
            wordtoSpan.setSpan(new ForegroundColorSpan(hlColor), keyStart,
                  name.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            Log.w(TAG, "unexpected keyStart: " + keyStart + " keyCount: " + keyCount);
        } else {
            wordtoSpan.setSpan(new ForegroundColorSpan(hlColor), keyStart,
                  keyStart + keyCount, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        return wordtoSpan;
    }

    //need open
    private void dial(CloudContact item) {
//        if (item.contactPhoneNum != null && item.contactPhoneNum.size() > 0) {
//            if (isCreator == 1) ActionCloudContactsCenter.updateCloudContactedCount(
//                    mContext, item.contactId);
//
//            String phoneNum = item.contactPhoneNum.get(0).phoneNum;
//            phoneNum = PhoneNumberArea.getInstance(mContext).replaceIpCall(phoneNum);
//
//            ActionCloudContactsCenter.sPhoneNum = phoneNum;
//            ActionCloudContactsCenter.sCloudDisplayName = item.contactName;
//            CommonCodeUtil.launchCallByNumber(mContext, phoneNum);
//        } else if (!TextUtils.isEmpty(item.contactUrl)) {
//            ContactInfoActivity.go2Url(mContext, item.contactUrl);
//        } else {
//            IphoneDialogUtil.showCustomMessageOK(mContext, -1, R.string.dialog_label_dial_none,
//                    R.string.dialog_label_dial_btn);
//        }
    }

    //need open
    private void displayCommunicationActivity(CloudContact item) {
        Intent intent = new Intent(mContext, CloudContactDetailActivity.class);
        intent.setAction(CloudContactDetailActivity.ACTION_CLOUD_CONTACT);
        intent.putExtra("contact_id", item.contactId);
        intent.putExtra("current_contact_id", contactId);
        intent.putExtra("group_id", item.groupId);
        intent.putExtra("group_name", mGroupName);
        intent.putExtra("user_id", item.userId);
        mContext.startActivityForResult(intent, Constants.ACTIVITY_REQUEST_DISPLAYCOMMUNICATION);

    }

    @Override
    public boolean onLongClick(View v) {
        ContactEntryHolder holder = (ContactEntryHolder) v.getTag();
        CloudContact item = holder.item;
        boolean ifLongClickDial = prefUtil.getPreference().getBoolean(
              PreferenceUtil.LONG_CLICK_DIAL, true);
        if (ifLongClickDial) {
            dial(item);
        } else {
            // setSelectedStatus(mTouchView);
            displayCommunicationActivity(item);
        }
        return true;
    }

    /*public void clearSelectedStatus(View view) {
        if (view != null) {
            ContactEntryHolder holder = (ContactEntryHolder) view.getTag();
            if (holder != null) {
                if (holder.contactId.equals(selectedId)) {
                    selectedId = null;
                }
                *//*holder.nameTextView.setTextColor(mContext.mSkinCommon.nameColor);
                holder.numberTextView.setTextColor(mContext.mSkinCommon.phoneColor);
                holder.orgTextView.setTextColor(mContext.mSkinCommon.jobTitleColor);

                holder.maskImg.setImageResource(R.drawable.mask);
                view.setBackgroundResource(R.color.transbg);*//*
            }
        }
    }*/

    @Override
    public void onClick(View v) {
        ContactEntryHolder holder = (ContactEntryHolder) v.getTag();

        /*selectedId = holder.contactId;
        if (mTouchedView != null) {
            ContactEntryHolder h = (ContactEntryHolder) mTouchedView.getTag();
            if (h == null) {
                return;
            }
            if (!h.contactId.equals(holder.contactId)) {
                clearSelectedStatus(mTouchedView);
                //notifyDataSetChanged();
            }

        }*/

        mTouchedView = v;

        //CloudContact item = (CloudContact)v.getTag(2);
        CloudContact item = holder.item;
        if (mIfCheckBoxShow) {
            if (item.userId.equals("0") && isHaveUnClickable) {
                Toast.makeText(mContext, "该用户未注册，不能进行如下操作", Toast.LENGTH_SHORT).show();
            } /*else if (item.userId.equals(prefUtil.getString(PreferenceUtil.CLIENT_USEID, "－1"))) {
                Toast.makeText(mContext, "对不起，您不能选择自己", Toast.LENGTH_SHORT).show();
            } */ else {
                boolean isChecked = holder.checkBox.isChecked();
                holder.checkBox.setChecked(!isChecked);
                ChatContact chatContact = null;
//                if (item.contactPhoneNum.size() > 0) {
//                    chatContact = new ChatContact(item.userId + "", item.contactName,  item.contactId + "", item.contact_image);
//                } else {
                chatContact = new ChatContact(item.userId + "", item.contactName, item.contactId + "", item.contact_image);
//                }

                if (isChecked) {


                    //mContactIdSelected.remove(chatContact);

                    for (ChatContact chatContact2 : mContactIdSelected) {
                        if (chatContact2.contactId.equals(chatContact.contactId)) {
                            mContactIdSelected.remove(chatContact2);
                            break;
                        }
                    }

                    for (CloudContact item2 : mSelectedContactList) {
                        if (item2.contactId.equals(item.contactId)) {
                            mSelectedContactList.remove(item2);

                            if (mIsShowSelected == true) {
                                mContactList.remove(item2);
                            }

                            break;


                        }
                    }


                    //mSelectedContactList.remove(item);


                } else {
                    if (CloudDialerActivity.isSingleChoose){
                        mContactIdSelected.clear();
                        mSelectedContactList.clear();
                    }
                    mContactIdSelected.add(chatContact);
                    mSelectedContactList.add(item);
                }
                mContext.sendMessageToHandler(Constants.FRESH_SEND_BUTTON_NUMBER);

                if (mIsShowSelected == false) {

                    int validsum = 0;
                    int invalidsum = 0;

                    for (CloudContact cloudContact : mContactList) {
                        String userId = cloudContact.userId;
                        if (isHaveUnClickable && userId.equals("0")) {
                            invalidsum++;
                        } else //if( mSelectedContactList.contains(cloudContact) == true )
                        {
                            for (CloudContact exsitone : mSelectedContactList) {
                                if (exsitone.contactId.equals(cloudContact.contactId)) {
                                    validsum++;
                                    break;
                                }
                            }
                        }
                    }

                    if ((invalidsum + validsum) == mContactList.size()) {
                        mContext.mCbSelectAll.setChecked(true);
                    } else {
                        mContext.mCbSelectAll.setChecked(false);
                    }

                }


            }

            notifyDataSetChanged();
        } else {
            boolean ifLongClickDial = prefUtil.getPreference().getBoolean(
                  PreferenceUtil.LONG_CLICK_DIAL, true);
            if (!ifLongClickDial) {
                dial(item);
            } else {
                if (opening) {
                    opening = false;
                    displayCommunicationActivity(item);
                }
            }
            mTouchedView = v;
            //setSelectedStatus(mTouchedView);

        }


    }

    public ArrayList<ChatContact> getSelectedContacts() {
        return mContactIdSelected;
    }

    public void clearSelected() {
        mContactIdSelected.clear();
    }

    public void selectAllContactIds(boolean select) {
        if (/*mContactIdSelected.size() == 0*/select == true)
        {
            ArrayList<ChatContact> chatContacts = new ArrayList<ChatContact>();
//          mSelectedContactList.clear();
//          mContactIdSelected.clear();
            for (CloudContact cloudContact : mContactList) {
                String itemcontactId = cloudContact.contactId;
                String userId = cloudContact.userId;
                if ( isHaveUnClickable && userId.equals("0") == true ) {
                }
                else
                {

                    boolean find = false;
                    for (CloudContact cloudContact2 : mSelectedContactList)
                    {
                        if(cloudContact2.contactId.equals(itemcontactId)  )
                        {
                            find = true;
                            break;
                        }
                    }

                    if( find == true )
                    {
                        continue;
                    }

                    String userName = cloudContact.contactName;
//                    String userPhone = cloudContact.contactPhoneNum.get(0).phoneNum;
                    String contactId = cloudContact.contactId + "";
                    String userImg = cloudContact.contact_image + "";
                    ChatContact chatContact = new ChatContact(userId, userName,  contactId, userImg);
                    chatContacts.add(chatContact);
                    mSelectedContactList.add(cloudContact);
                }
            }
            mContactIdSelected.addAll(chatContacts);


            if (chatContacts.size() != 0) {
                mContext.setSelectImage(true);
            }

        }
        else
        {
//        	mContactIdSelected.clear();
//          mSelectedContactList.clear();
            for (CloudContact cloudContact : mContactList) {
                String userId = cloudContact.userId;
                if (isHaveUnClickable && userId.equals("0")) {
                } else {
                    for (CloudContact cloudContact2 : mSelectedContactList) {
                        if (cloudContact2.userId.equals(userId)) {
                            mSelectedContactList.remove(cloudContact2);
                            break;
                        }
                    }

                    for (ChatContact chatContact : mContactIdSelected) {
                        if (chatContact.userId.equals(userId)) {
                            mContactIdSelected.remove(chatContact);
                            break;
                        }
                    }

                }
            }


            mContext.setSelectImage(false);
        }
        Log.i("size++", mContactList.size() + "");
        notifyDataSetChanged();
    }

    /**
     * 改变数据
     *
     * @param cloudContacts
     */
    public void changeContent(ArrayList<CloudContact> cloudContacts) {
        mContactList = cloudContacts;
        notifyDataSetChanged();
    }

    /**
     * 仅显示已选
     */
    public void changeSelectedContent() {
        mIsShowSelected = true;
        mBackUpContactList.clear();
        mBackUpContactList.addAll(mContactList);
        mContactList.clear();
        mContactList.addAll(mSelectedContactList);
        ArrayList<ChatContact> chatContacts = new ArrayList<ChatContact>();
        mContactIdSelected.clear();
        for (CloudContact cloudContact : mContactList) {
            String userId = cloudContact.userId;
            String userName = cloudContact.contactName;
//            String userPhone = cloudContact.contactPhoneNum.get(0).phoneNum;
            String contactId = cloudContact.contactId + "";
            String userImg = cloudContact.contact_image + "";
            ChatContact chatContact = new ChatContact(userId, userName, contactId, userImg);
            chatContacts.add(chatContact);
        }
        mContactIdSelected.addAll(chatContacts);
        notifyDataSetChanged();
    }

    /**
     * 恢复到全部
     */
    public void changeToAllContent() {
        if (mIsShowSelected) {
            mContactList.clear();
            mContactList.addAll(mBackUpContactList);
            mIsShowSelected = false;
        }

        ArrayList<ChatContact> chatContacts = new ArrayList<ChatContact>();
        for (CloudContact cloudContact : mSelectedContactList) {
            String userId = cloudContact.userId;
            String userName = cloudContact.contactName;
//            String userPhone = cloudContact.contactPhoneNum.get(0).phoneNum;
            String contactId = cloudContact.contactId + "";
            String userImg = cloudContact.contact_image + "";
            ChatContact chatContact = new ChatContact(userId, userName, contactId, userImg);
            chatContacts.add(chatContact);
        }
        mContactIdSelected.clear();
        mContactIdSelected.addAll(chatContacts);

        mContext.sendMessageToHandler(Constants.FRESH_SEND_BUTTON_NUMBER);


        int validsum = 0;
        int invalidsum = 0;

        for (CloudContact cloudContact : mContactList) {
            String userId = cloudContact.userId;
            if (isHaveUnClickable && userId.equals("0")) {
                invalidsum++;
            } else //if( mSelectedContactList.contains(cloudContact) == true )
            {
                for (CloudContact exsitone : mSelectedContactList) {
                    if (exsitone.contactId.equals(cloudContact.contactId)) {
                        validsum++;
                        break;
                    }
                }
            }
        }

        if ((invalidsum + validsum) == mContactList.size()) {
            mContext.mCbSelectAll.setChecked(true);
        } else {
            mContext.mCbSelectAll.setChecked(false);
        }


        notifyDataSetChanged();
    }

    public void selectContactIds(ArrayList<ChatContact> list) {
        if (mSelectedContactList == null) {
            mSelectedContactList = new ArrayList<CloudContact>();
        }
        mContactIdSelected.clear();
        mContactIdSelected.addAll(list);
        /*
        mSelectedContactList.clear();
        if(list != null && list.size()>0){
            for(int i=0;i<list.size();i++){
                String contactId = list.get(i).contactId;
                for(int j=0;j<mContactList.size();j++){
                    if((mContactList.get(j).contactId+"").equals(contactId)){
                        mSelectedContactList.add(mContactList.get(j));
                    }
                }
            }
        }*/
        this.notifyDataSetChanged();
    }

    /*public void clearSelectedStatus() {
        if (mTouchedView != null) {
            ContactEntryHolder holder = (ContactEntryHolder) mTouchedView.getTag();
            if (holder != null) {
                holder.nameTextView.setTextColor(mContext.mSkinCommon.nameColor);
                holder.numberTextView.setTextColor(mContext.mSkinCommon.phoneColor);
                holder.orgTextView.setTextColor(mContext.mSkinCommon.jobTitleColor);
                holder.maskImg.setImageResource(R.drawable.mask);
                mTouchedView.setBackgroundResource(R.color.transbg);
            }
        }
        notifyDataSetChanged();
    }*/

    public void setIfCheckBoxShow(boolean show) {
        this.mIfCheckBoxShow = show;
        mContactIdSelected.clear();
        //selectedId = null;
    }

    public void setIfCheckBoxShow(boolean show, ArrayList<ChatContact> list) {
        this.mIfCheckBoxShow = show;
        mContactIdSelected.clear();
        mContactIdSelected.addAll(list);
        mSelectedContactList.clear();
        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
//                String contactId = list.get(i).contactId;
//                for(int j=0;j<mContactList.size();j++){
//                    if((mContactList.get(j).contactId+"").equals(contactId)){
//                        mSelectedContactList.add(mContactList.get(j));
//                    }
//                }
                CloudContact cloudContact = new CloudContact();
//                ArrayList<PhoneNumItem> contactPhoneNum = new ArrayList<PhoneNumItem>();
                cloudContact.contactId = list.get(i).contactId;
                cloudContact.contactName = list.get(i).userName;
                cloudContact.userId = list.get(i).userId;
//                PhoneNumItem phoneNumItem = new PhoneNumItem();
//                phoneNumItem.phoneNum = list.get(i).getUserPhone();
//                phoneNumItem.label = PhoneNumberArea.getInstance(mContext).getArea(list.get(i).getUserPhone(), true);
//                contactPhoneNum.add(0, phoneNumItem);
//                cloudContact.contactPhoneNum = contactPhoneNum;
                cloudContact.contact_image = list.get(i).getUserImg();
                mSelectedContactList.add(cloudContact);
            }
        }
        mContext.sendMessageToHandler(Constants.FRESH_SEND_BUTTON_NUMBER);
    }

    /*public void setSelectedStatus(View view) {
        if (view != null) {
            ContactEntryHolder holder = (ContactEntryHolder) view.getTag();
            if (holder != null) {
                *//*holder.nameTextView.setTextColor(Color.WHITE);
                holder.orgTextView.setTextColor(Color.WHITE);
                holder.numberTextView.setTextColor(Color.WHITE);
                holder.maskImg.setImageResource(R.drawable.mask_pressed);
                view.setBackgroundResource(R.drawable.centersel_pressed);*//*
            }
        }
        //notifyDataSetChanged();
    }*/

    private boolean isHaveUnClickable = false;

    public void setCloudContactCheckStyle(boolean isHaveUnClickable) {
        this.isHaveUnClickable = isHaveUnClickable;
    }


    public static final class ContactEntryHolder {

        public ImageView contactDisturbStatus;

        public CheckBox checkBox;

        public TextView nameTextView;

        public TextView timesContactedView;

        public TextView orgTextView;

        public TextView numberTextView;

        public RoundImageView quickContact;

        public Long contactId;

        public String phoneNum;

        public ImageView wxIcon;

        //public ImageView maskImg;

        public ImageView cloudStatus;
        public ImageView inviteImg;


        //////////////////////////////////

        public CloudContact item;

    }

    /**
     * 未注册联系人邀请
     */
    private void inviteContact(String contactId) {
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID,
              LocalLogin.getInstance().mSid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_CONTACT_ID, contactId));
        GetInviteContactMsg getInviteContactMsg = new GetInviteContactMsg(
              mHandler.obtainMessage(MSG_INVITE_CONTACT));
        getInviteContactMsg.mApi = AsynHttpClient.API_CONTACT_INVITE;
        getInviteContactMsg.mParams = nvps;
        AsynHttpClient.getInstance(mContext).execCcHttp(getInviteContactMsg);
    }
}